/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.hertzbeat.alert;

import lombok.extern.slf4j.Slf4j;
import org.apache.hertzbeat.common.entity.alerter.Alert;
import org.apache.hertzbeat.common.queue.CommonDataQueue;
import org.apache.hertzbeat.plugin.Plugin;
import org.apache.hertzbeat.plugin.PostAlertPlugin;
import org.apache.hertzbeat.plugin.runner.PluginRunner;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

/**
 * Alarm information storage and distribution
 */
@Component
@Slf4j
public class DispatcherAlarm implements InitializingBean {

    private static final int DISPATCH_THREADS = 3;

    private final AlerterWorkerPool workerPool;
    private final CommonDataQueue dataQueue;
    private final AlertStoreHandler alertStoreHandler;

    public DispatcherAlarm(AlerterWorkerPool workerPool,
                           CommonDataQueue dataQueue,
                           AlertStoreHandler alertStoreHandler,
                           PluginRunner pluginRunner) {
        this.workerPool = workerPool;
        this.dataQueue = dataQueue;
        this.alertStoreHandler = alertStoreHandler;
    }

    @Override
    public void afterPropertiesSet() {
        // Start alarm distribution
        DispatchTask dispatchTask = new DispatchTask();
        for (int i = 0; i < DISPATCH_THREADS; i++) {
            workerPool.executeJob(dispatchTask);
        }
    }

    private class DispatchTask implements Runnable {
        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    Alert alert = dataQueue.pollAlertsData();
                    if (alert != null) {
                        // Determining alarm type storage
                        alertStoreHandler.store(alert);
                    }
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
            }
        }
    }

}
